/*    file: PcmFileSource.cpp
 *    desc:
 * 
 * created: 2017-04-15
 *  author: chuanjiang.zh@qq.com
 * company: 
 */

#include "PcmFileSource.h"


PcmFileSource::PcmFileSource():
	m_sink(),
	m_file(),
	m_pts(),
	m_packetSize(160)
{

}

PcmFileSource::~PcmFileSource()
{
	close();
}

void PcmFileSource::setSink(PcmFileSourceSink* sink)
{
	m_sink = sink;
}

bool PcmFileSource::open(const char* filename)
{
	close();

	fopen_s(&m_file, filename, "rb");
	if (!m_file)
	{
		return false;
	}

	m_filename = filename;

	return start();
}

void PcmFileSource::close()
{
	if (isRunning())
	{
		stop();
	}

	if (m_file)
	{
		fclose(m_file);
		m_file = NULL;
	}

	m_pts = 0;
}

bool PcmFileSource::isOpen()
{
	return isRunning();
}

void PcmFileSource::setPacketSize(int size)
{
	if (size > 0 && size < 1024 * 2)
	{
		m_packetSize = size;
	}
}

int PcmFileSource::run()
{
	while (!m_canExit)
	{
		const size_t BUFFER_SIZE = 1024 * 2;
		char buffer[BUFFER_SIZE];
		size_t length = fread(buffer, 1, m_packetSize, m_file);
		if (length == m_packetSize)
		{
			if (m_sink)
			{
				m_sink->onPcmData((uint8_t*)buffer, length, m_pts);
			}

			m_pts += length;
		}
		else
		{
			fseek(m_file, 0, SEEK_SET);
		}

		m_event.timedwait(20);
		
	}
	return 0;
}

void PcmFileSource::doStop()
{
	m_event.post();
}


